package dao.impl;

import java.util.ArrayList;

import dao.IStudentDao;
import entity.Student;

public class StudentDaoImpl implements IStudentDao{
	private ArrayList<Student> students = new ArrayList<>();
	@Override
	public boolean save(Student t) {
		if(students.contains(t)){
			return false;
		}
		return students.add(t);
	}

	@Override
	public boolean delete(Student t) {
		if(students.contains(t)){
			students.remove(t);
			return true;
		}
		return false;
	}

	@Override
	public boolean update(Student t) {
		int index = students.indexOf(t);
		if(-1 != index){
			students.set(index, t);
			return true;
		}
		return false;
	}

	@Override
	public Student selectById(int id) {
		for (Student student : students) {
			if(id == student.getId()){
				return student;
			}
		}
		return null;
	}

	@Override
	public ArrayList<Student> selectAll() {
		return students;
	}

	@Override
	public ArrayList<Student> selectByName(String name) {
		ArrayList<Student> arr = new ArrayList<Student>();
		for (Student student : students) {
			if(student.getName().equals(name)){
				arr.add(student);
			}
		}
		return arr;
	}

	@Override
	public ArrayList<Student> selectByScore(int low, int high) {
		ArrayList<Student> arr = new ArrayList<Student>();
		for (Student student : students) {
			if(student.getScore() >= low && student.getScore() <= high){
				arr.add(student);
			}
		}
		return arr;
	}

	@Override
	public ArrayList<Student> sortByScoreDesc() {
		ArrayList<Student> copy = new ArrayList<Student>(students);
		copy.sort((s1,s2) -> s2.getScore() - s1.getScore());
		return copy;
	}

}
